<?php
error_reporting(E_ALL & ~E_NOTICE);
defined('__ROOT__') or define('__ROOT__',dirname(dirname(dirname(__FILE__))));
require __ROOT__.'/comm/mysql.php';
$items = require(__ROOT__.'/config/item.php');
$pr_total = 0;
$pr_sliding=[];
$user_id = intval($_GET['user_id']);
if($user_id<=0){
	res(400,'wrong user_id');
}
//这里可以查询数据库验证用户,这里没用户,也没登录,只要ID格式正确都信任

foreach($items as $item_id=>$item){
	//$pr_sliding[$item_id]['start'] = $pr_total;//这个不需要的了一边就够了
	$pr_total +=$item['pr'];
	$pr_sliding[$item_id]['end'] = $pr_total; //生成sliding的界限
}
$hit = rand(0,$pr_total);
foreach($pr_sliding as $item_id=>$pr){
	if($hit < $pr['end']){
		$pdo->beginTransaction();
		$count = $pdo->exec("UPDATE `award_items` SET status=1 where item_id={$item_id}  AND status=0 LIMIT 1");
		//echo $count;
		if($count == 0){
			$pdo->commit();
			res(404,'谢谢惠顾');
		}else{
			$item = $items[$item_id];
			$ins_count = $pdo->exec("INSERT INTO `user_award`(`user_id`,`award_rate`,`award_result`,created_at)VALUES({$user_id},{$item['pr']},{$item['item']},".time().')');
			if($ins_count<=0){
				$pdo->rollback();
				res(500,'系统故障');
			}else{
				$pdo->commit();
				res(200,"恭喜您中奖了",$item);
			}
		}
	}
}

function res($status,$msg,$data=null){
	$array=[
		'status'=>$status,
		'msg'=>$msg,
		'data'=>$data
	];
	header("content:application/json;chartset=uft-8");
	echo json_encode($array);
	die();
}